(async function () {
    const koa = require('koa')
    const Router = require('koa-router')
    const bodyParser = require('koa-bodyparser')
    const mysql = require('mysql2/promise')
    const fs = require('fs')

    const app = new koa()
    const router = new Router()
    app.use(bodyParser())

    const connection = await mysql.createConnection({
        host: '127.0.0.1',
        port: '5690',
        user: 'root',
        password: 'king+5688',
        database: 'king'
    })

    router.get('/', ctx => {
        let data = fs.readFileSync('./static/index.html')
        ctx.body = data.toString()
    })

    router.get('/todo', async ctx => {
        let [todo] = await connection.query('SELECT id,title,done FROM todo')
        ctx.body = {
            code: 0,
            data: todo
        }
    })

    router.post('/add', async ctx => {
        let title = ctx.request.body.title || ''
        if (title == '') {
            ctx.body = {
                code: 1,
                data: 'title不能为空'
            }
            return;
        }
        let [data] = await connection.query(`INSERT INTO todo (title,done) VALUES (${title},0)`)
        if (data.affectedRows > 0) {    // 影响的数量大于0则操作成功
            ctx.body = {
                code: 0,
                data: '添加成功'
            }
        }

    })

    router.post('/del', async ctx => {
        let id = ctx.request.body.id || ''
        if (!!id) {
            let [data] = await connection.query('DELETE FROM todo WHERE id=' + id)
            if (data.affectedRows > 0) {
                ctx.body = {
                    code: 0,
                    data: '删除成功'
                }
            }
        } else {
            ctx.body = {
                code: 1,
                data: "删除成功，id不能为空"
            }
        }
    })

    router.post('/change', async ctx => {
        let id = ctx.request.body.id || ''
        let done = Number(ctx.request.body.done) || ''

        if (!!id) {
            let [data] = await connection.query('UPDATE todo SET ??=? WHERE ??=?', ['done', done, 'id', id])
            if (data.affectedRows > 0) {
                ctx.body = {
                    code: 0
                }
            } else {
                ctx.body = {
                    code: 1,
                    data: '更改出现错误'
                }
            }
        } else {
            ctx.body = {
                code: 1,
                data: '更改状态id为空'
            }
        }
    })

    app.use(router.routes())

    app.listen(80)
})()